<script setup>
import { ref } from 'vue'

// 响应式数据
const loginForm = ref({
  UserAccount: '',
  UserPassword: ''
})

// 引用表单
const loginFormRef = ref(null)

import { userLoginService, userRegisterAPI } from '@/api/user'
import { useRouter } from 'vue-router'
import { useUserStore, useUserCollectionStore } from '@/stores'
import { ElMessage } from 'element-plus'

const router = useRouter()

const userStore = useUserStore()
const userCollectionStore = useUserCollectionStore()
const handleSubmit = async () => {
  await loginFormRef.value.validate()
  const res = await userLoginService({
    UserPassword: loginForm.value.UserPassword,
    UserName: loginForm.value.UserAccount
  })
  console.log('登录接口返回:', res)
  console.log('res.data:', res.data)
  if (res.data == 'no') {
    userStore.setToken(loginForm.value.UserAccount)
    userStore.setUserInfo(loginForm.value.UserAccount, loginForm.value.UserPassword)
    ElMessage.success('登录成功')
    router.push('/home/user/index')
  } else if (
    typeof res.data === 'string' &&
    res.data.charCodeAt(0) >= 48 &&
    res.data.charCodeAt(0) <= 57
  ) {
    const collection = ref([])
    collection.value = res.data.trim().split(/\s+/)
    userCollectionStore.removeUserCollectionInfo()
    userCollectionStore.setUserCollectionInfo(collection.value)
    ElMessage.success('登录成功')
    router.push('/home/user/index')
  } else if (res.data == 'fj') {
    ElMessage.error('账号被封禁')
  } else {
    ElMessage.error('账号或密码错误')
  }
}

const qiehuan = () => {
  showLogin.value = !showLogin.value
}

const showLogin = ref(true)
const registerForm = ref({
  UserAccount: '',
  UserPassword: '',
  UserName: '',
  UserPhoneNumber: '',
  UserSex: '男',
  Status: '1'
})

// 注册表单验证规则
const registerFormRules = {
  UserAccount: [
    { required: true, message: '账号不能为空', trigger: 'blur' },
    { min: 6, max: 6, message: '账号必须是6位', trigger: 'blur' }
  ],
  UserPassword: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 10, message: '密码长度必须为6-10位', trigger: 'blur' }
  ],
  UserName: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  UserPhoneNumber: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { len: 11, message: '手机号必须是11位', trigger: 'blur' }
  ],
  UserSex: [{ required: true, message: '请选择性别', trigger: 'change' }]
}

const registerFormRef = ref(null)

const sendRegister = async () => {
  // 验证表单
  await registerFormRef.value.validate()

  // 调用注册API
  const res = await userRegisterAPI(registerForm.value)

  // 处理不同的返回值
  if (res.data === -1) {
    ElMessage.error('用户名已存在，请选择其他用户名')
  } else if (res.data === -2) {
    ElMessage.error('账号已存在，请选择其他账号')
  } else if (res.data === 1) {
    showLogin.value = true
    ElMessage.success('注册成功')
  } else {
    ElMessage.error('注册失败，请重试')
  }
}
</script>

<template>
  <el-row class="login-page" v-if="showLogin">
    <el-col :span="12" :offset="6" class="login-form-page">
      <div class="loginbox">
        <h3 class="login-title">欢迎登录付费问答系统</h3>
        <el-form :model="loginForm" ref="loginFormRef" label-width="80px" class="login-form">
          <el-form-item label="用户名" prop="UserAccount">
            <el-input v-model="loginForm.UserAccount" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="密码" prop="UserPassword" show-password>
            <el-input type="password" v-model="loginForm.UserPassword" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSubmit" class="but">登录</el-button>
          </el-form-item>
          <div class="register" @click="qiehuan()">没有账号？立即注册</div>
        </el-form>
      </div>
    </el-col>
  </el-row>

  <el-row class="login-page" v-else>
    <el-col :span="12" :offset="6" class="login-form-page">
      <div class="registerbox">
        <h3 class="login-title">注册账号</h3>
        <el-form
          :model="registerForm"
          ref="registerFormRef"
          :rules="registerFormRules"
          label-width="80px"
          class="login-form"
        >
          <el-form-item label="账号" prop="UserAccount">
            <el-input v-model="registerForm.UserAccount" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="密码" prop="UserPassword">
            <el-input
              type="password"
              v-model="registerForm.UserPassword"
              placeholder="请输入密码"
              show-password
            />
          </el-form-item>
          <el-form-item label="用户名" prop="UserName">
            <el-input v-model="registerForm.UserName" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="手机号" prop="UserPhoneNumber">
            <el-input v-model="registerForm.UserPhoneNumber" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="性别" prop="UserSex">
            <el-select v-model="registerForm.UserSex" placeholder="请选择性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="sendRegister()" class="but">注 册</el-button>
          </el-form-item>
          <div class="register" @click="qiehuan()">已有账号？立即登录</div>
        </el-form>
      </div>
    </el-col>
  </el-row>
</template>

<style scoped>
.register {
  padding-top: 15px;
  padding-left: 20px;
  text-align: center;
  font-size: 12px;
  cursor: pointer;
}

.login-page {
  height: 100vh;
  background-color: #fff;
  background-image: url('@/assets/image.png');
  background-size: cover;
  background-position: center;
}

.loginbox,
.registerbox {
  width: 300px;
  border-radius: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
  font-weight: bold;
}

.login-form-page {
  display: flex;
  justify-content: center;
  align-items: center;
}

.but {
  width: 100%;
}
</style>
